<template>
  <div>
    <el-form ref="form" label-width="80px" :model="spu">
      <el-form-item label="SPU名称">
        <el-input v-model="spu.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spu.tmId">
          <el-option
            :label="tm.tmName"
            :value="tm.id"
            v-for="(tm, index) in tradeMarkList"
            :key="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input type="textarea" row="4" v-model="spu.description"></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
          action="/dev-api/admin/product/upload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :file-list="spuImageList"
          :on-success="handleSUccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          :placeholder="`还有个${unselectSaleAttr.length}未选择`"
          v-model="attrIdAddAttrName"
        >
          <el-option
            :label="unselect.name"
            :value="`${unselect.id}:${unselect.name}`"
            v-for="(unselect, index) in unselectSaleAttr"
            :key="unselect.id"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!attrIdAddAttrName"
          @click="addSaleAttr"
          >添加销售属性</el-button
        >
        <el-table style="width: 100%" border :data="spu.spuSaleAttrList">
          <el-table-column type="index" label="序号" width="80" align="center">
          </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="150">
          </el-table-column>
          <el-table-column
            prop="spuSaleAttrValueList"
            label="属性值名称列表"
            width="width"
          >
            <template v-slot="{ row, $index }">
              <el-tag
                :key="tag.id"
                v-for="(tag, index) in row.spuSaleAttrValueList"
                closable
                :disable-transitions="false"
                @close="handleClose(row, index)"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>

              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConFirm(row)"
                @blur="handleInputConFirm(row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="addSaleAttrValue(row)"
                >添加</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="150">
            <template v-slot="{ row, $index }">
              <el-button
                type="danger"
                size="mini"
                @click="deleteSaleAttr(spu.spuSaleAttrList, $index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdataSpuinfo">保存</el-button>
        <el-button @click="ChangeScene">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "SpuForm",
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: "",
      spu: {
        category3Id: "",
        description: "",
        tmId: "",
        spuImageList: [
          // {
          //   id: 0,
          //   imgName: "string",
          //   imgUrl: "string",
          //   spuId: 0,
          // },
        ],
        spuName: "",
        spuSaleAttrList: [
          /*     {
            baseSaleAttrId: 0,
            id: 0,
            saleAttrName: "",
            spuId: 0,
            spuSaleAttrValueList: [
               {
                baseSaleAttrId: 0,
                id: 0,
                isChecked: "string",
                 saleAttrName: "string",
                saleAttrValueName: "string",
                spuId: 0,
               },
            ],
          }, */
        ],
      },
      tradeMarkList: [],
      spuImageList: [],
      saleAttrList: [],
      //收集未选择销售属性的id和属性名
      attrIdAddAttrName: "",
    };
  },
  methods: {
    //照片删除的回调
    handleRemove(file, fileList) {
      // console.log(file, fileList);
      this.spuImageList = fileList;
    },
    //照片墙预览的回调
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      //控制dialog显示与隐藏
      this.dialogVisible = true;
    },
    //照片添加的回调
    handleSUccess(response, file, fileList) {
      // console.log(response);
      this.spuImageList = fileList;
    },
    //传scene数据给父组件(触发自定义事件)
    ChangeScene() {
      this.$emit("getspuFormscene", {
          scene: 0,
          flag: this.spu.id ? "修改" : "添加",
        });
    },
    //初始化spuForm的数据 得到父组件传来的数据 再发送请求
    async initSpuData(spu) {
      let spuResult = await this.$API.spu.reqSpu(spu.id);
      if (spuResult.code == 200) {
        this.spu = spuResult.data;
      }
      let tradeMarkResult = await this.$API.spu.reqTradeMarkList();
      if (tradeMarkResult.code == 200) {
        this.tradeMarkList = tradeMarkResult.data;
      }
      let spuImageResult = await this.$API.spu.reqSpuImageList(spu.id);
      if (spuImageResult.code == 200) {
        //在对象里面定义name和url属性名  elementUI 的file-list才能识别，才能显示图片
        //!!注意:这里要注意到vue能否监测到新增的数据,是否是响应式的数据 想想新增的数据 vue怎样才能监测到 有那些方法
        /*  let listArr = spuImageResult.data;
        listArr.forEach((element) => {
          element.name = element.imgName;
          element.url = element.imgUrl;
        });
        this.spuImageList = listArr; */
        this.spuImageList = spuImageResult.data;
        this.spuImageList.forEach((element) => {
          /*  这里添加的就不是响应式的  但是这里这样用没有问题 这里并不需要响应式的数据
           element.name = element.imgName;
           element.url = element.imgUrl; */
          this.$set(element, "name", element.imgName);
          this.$set(element, "url", element.imgUrl);
        });
      }
      //销售属性的数据
      let saleResult = await this.$API.spu.reqBaseSaleAttrList();
      if (saleResult.code == 200) {
        this.saleAttrList = saleResult.data;
      }
    },
    //初始化添加SPU数据
    async initAddSpuData(Category3id) {
      //获得品牌列表的数据
      let tradeMarkResult = await this.$API.spu.reqTradeMarkList();
      if (tradeMarkResult.code == 200) {
        this.tradeMarkList = tradeMarkResult.data;
      }
      //销售属性的数据
      let saleResult = await this.$API.spu.reqBaseSaleAttrList();
      if (saleResult.code == 200) {
        this.saleAttrList = saleResult.data;
      }
      this.spu.category3Id = Category3id;
    },
    //点击×的回调
    handleClose(row, index) {
      row.spuSaleAttrValueList.splice(index, 1);
    },

    //添加另外的销售属性
    addSaleAttr() {
      let [baseSaleAttrId, saleAttrName] = this.attrIdAddAttrName.split(":");
      let newSaleAttr = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
      };
      this.spu.spuSaleAttrList.push(newSaleAttr);
      this.attrIdAddAttrName = "";
    },
    //添加销售属性值的回调
    addSaleAttrValue(row) {
      this.$set(row, "inputVisible", true);
      this.$set(row, "inputValue", "");
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus();
      });
    },
    //失去属性值焦点的回调
    handleInputConFirm(row) {
      console.log(row);
      const { baseSaleAttrId, inputValue } = row;
      //属性值不能为空
      if (inputValue.trim() == "") {
        this.$message("属性值不能为空");
        return;
      }
      //属性值不能重复
      let result = row.spuSaleAttrValueList.some((element) => {
        if (element.saleAttrValueName == row.inputValue) {
          return true;
        }
      });
      if (result) {
        this.$message("属性值不能重复");
        return;
      }
      //想向数组中添加数据
      let newSaleAttrValue = { baseSaleAttrId, saleAttrValueName: inputValue };
      row.spuSaleAttrValueList.push(newSaleAttrValue);
      row.inputVisible = false;
    },
    //删除销售属性的回调
    deleteSaleAttr(spuSaleAttrList, index) {
      spuSaleAttrList.splice(index, 1);
    },
    //保存按钮的回调
    async addOrUpdataSpuinfo() {
      //先将需要发送请求的数据整理好，再发送请求
      this.spu.spuImageList = this.spuImageList.map((item) => {
        return {
          imgName: item.name,
          imgUrl: (item.response && item.response.data) || item.url,
        };
      });
      let result = await this.$API.spu.reqAddOrUpdataSpuInfo(this.spu);
      if (result.code == 200) {
      this. ChangeScene()
      }
    },
  },
  computed: {
    //收集剩余的销售属性
    unselectSaleAttr() {
      //!!注意这里的逻辑！！
      let result = this.saleAttrList.filter((item) => {
        return this.spu.spuSaleAttrList.every((element) => {
          if (element.saleAttrName !== item.name) {
            return true;
          }
        });
      });
      return result;
    },
  },
};
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>